package com.chatplus.application.aiprocessor.platform.chat.chatgpt;

import cn.bugstack.openai.executor.model.chatgpt.config.ChatGPTConfig;
import cn.bugstack.openai.executor.parameter.CompletionRequest;
import cn.bugstack.openai.session.Configuration;
import cn.bugstack.openai.session.OpenAiSession;
import cn.bugstack.openai.session.defaults.DefaultOpenAiSessionFactory;
import com.chatplus.application.aiprocessor.interceptor.DynamicKeyHandleInterceptor;
import com.chatplus.application.aiprocessor.listener.CommonEventSourceListener;
import com.chatplus.application.aiprocessor.platform.chat.ChatProcessorService;
import com.chatplus.application.aiprocessor.provider.ChatAiProcessorServiceProvider;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.enumeration.AiPlatformEnum;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * ChatGPT 机器人处理器
 *
 * @author chj
 * @date 2023/12/27
 **/
@Service(value = ChatAiProcessorServiceProvider.SERVICE_NAME_PRE + "OPENAI")
public class ChatGPTProcessor extends ChatProcessorService {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(ChatGPTProcessor.class);

    @Override
    public void processStream() throws Exception {
        CompletionRequest request = getCompletionRequest();
        // 3. 应答请求
        OpenAiSession openAiSession = getSessionFactory();
        if (openAiSession != null) {
            openAiSession.completions(request, new CommonEventSourceListener(chatRequest));
        }
    }

    @Override
    public String processSync() {
        CompletionRequest request = getCompletionRequest();
        // 3. 应答请求
        OpenAiSession openAiSession = getSessionFactory();
        if (openAiSession != null) {
            try {
                CompletableFuture<String> completions = openAiSession.completions(request);
                return completions.get();
            } catch (Exception e) {
                LOGGER.message("ChatGPTProcessor processSync error").exception(e).error();
            }
        }
        return "";
    }
    @Override
    public AiPlatformEnum getChannel() {
        return AiPlatformEnum.OPEN_AI;
    }

    @Override
    public synchronized OpenAiSession getSessionFactory() {
        instance();
        // 单独设置链接
        openApiKey.forEach(item -> {
            if (!item.getUrl().contains(ChatGPTConfig.V1_CHAT_COMPLETIONS)) {
                item.setUrl(item.getUrl().concat(ChatGPTConfig.V1_CHAT_COMPLETIONS));
            }
        });
        // 2. 配置文件
        Configuration configuration = new Configuration();
        configuration.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        // 3. 会话工厂
        DefaultOpenAiSessionFactory factory = new DefaultOpenAiSessionFactory(configuration);
        factory.setInterceptor(new DynamicKeyHandleInterceptor(openApiKey, getChannel()));
        return factory.openSession();
    }

}
